import fetch from "../../utils/fetch";

Page({

  /**
   * 页面的初始数据
   */
  data: {
    fromId: 1,
    time:'早餐',
    recordDate: '',
    oftenSearch:[],
    value:'', //输入框内容
    isShow: false, //展示搜索结果
    foodData: [
      {
        id: "baiyulvsewutangdoujiang",
        name: "白玉绿色无糖豆浆",
        img: "http://image.hpcn21.com/upfiles/food/201410/4225/sa20141231113529.jpg",
        heat_cal: "27.00 千卡"
      },
      {
        id: "bingquannvrendoujiang",
        name: "冰泉女人豆浆",
        img: "http://image.hpcn21.com/upfiles/food/201410/4206/sa20141229092719.jpg",
        heat_cal: "382.00 千卡"
      },
      {
        id: "doujiang",
        name: "豆浆",
        img: "http://image.hpcn21.com/upfiles/food/201410/1161/sa2014090211112614.jpg",
        heat_cal: "16.00 千卡"
      },
      {
        id: "doujiangfen",
        name: "豆浆粉",
        img: "http://image.hpcn21.com/upfiles/food/201410/20141004032538/sa201410041532538.jpg",
        heat_cal: "426.00 千卡"
      },
      {
        id: "doujiangtian",
        name: "豆浆(甜)",
        img: "http://image.hpcn21.com/upfiles/food/201410/20141004030020/sa201410041530020.jpg",
        heat_cal: "33.00 千卡"
      },
      {
        id: "guligulihongdounongjiang",
        name: "谷粒谷力红豆浓浆",
        img: "http://image.hpcn21.com/upfiles/food/201410/4204/sa20141225180513.jpg",
        heat_cal: "116.00 千卡"
      },
      {
        id: "huangdouhongdoulianzibaihedoujiang",
        name: "黄豆红豆莲子百合豆浆",
        img: "http://image.hpcn21.com/upfiles/food/202008/sa20200818144448.jpg",
        heat_cal: "329.00 千卡"
      },
      {
        id: "huangweipaichundoujianggan",
        name: "皇味牌纯豆浆(干)",
        img: "http://image.hpcn21.com/upfiles/food/201410/4220/sa20141229172934.jpg",
        heat_cal: "375.00 千卡"
      },
      {
        id: "longdanvrendoujiang",
        name: "隆达女人豆浆",
        img: "http://image.hpcn21.com/upfiles/food/201410/4185/sa20141224173705.jpg",
        heat_cal: "220.00 千卡"
      },
      {
        id: "weiweiyingyanggudonghongdounongjiang",
        name: "维维营养谷动红豆浓浆",
        img: "http://image.hpcn21.com/upfiles/food/201410/4224/sa20141231113146.jpg",
        heat_cal: "137.00 千卡"
      },
      {
        id: "yongheheidoujiang",
        name: "永和黑豆浆",
        img: "http://image.hpcn21.com/upfiles/food/201410/2591/sa2014102711111722.jpg",
        heat_cal: "162.00 千卡"
      }
    ],
    searchData:[],
    show: false,
    selectedSport: {},
    totalHeat: 0,
    unitHeat:0,
    recordSport: []
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    const fromId = options.fromId;
    const recordDate = options.recordDate;
    const time = options.time;
    let tempArr = [];
    // 读取缓存中的历史搜索记录
    if(fromId == 1){
      tempArr = wx.getStorageSync('food')?JSON.parse(wx.getStorageSync('food')):[];
    }else{
      tempArr = wx.getStorageSync('sport')?JSON.parse(wx.getStorageSync('sport')):[];
    }
    this.setData({oftenSearch:tempArr,
    fromId,time,recordDate});
  },
  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    const fromId = this.data.fromId;
    if(fromId== 1){
      wx.setStorageSync('food', JSON.stringify(this.data.oftenSearch));
    }else{
      wx.setStorageSync('sport', JSON.stringify(this.data.oftenSearch));
    }
  },
  // 防抖
  timer : null,
  // 搜索
  search(e){
    const that = this;
    clearTimeout(this.timer);
    this.timer = setTimeout(()=>{
      const value = e.detail.value;
      if(value){
        const oftenSearch = this.data.oftenSearch;
        let i;
        // 在历史搜索里
        for (i = 0; i < oftenSearch.length; i++) {
          if (oftenSearch[i] == value) {
            break;
          }
        }
        // 不在历史搜索，加入到历史搜索栈顶
        if (i >= oftenSearch.length)
          oftenSearch.unshift(value);
          if(this.data.fromId==1){
            fetch(`/food/search?value=${value}`).then(res=>{
              this.setData({
                oftenSearch: oftenSearch,
                // foodData: res.data,
                searchData: res.data,
                isShow: true,
              })
            })
          }else{
            // console.log(222);
            fetch(`/sports/search?value=${value}`).then(res=>{
              console.log(res);
              this.setData({
                oftenSearch,
                isShow: true,
                searchData: res.data
              })
            })
          }
      }else{
        this.setData({
          isShow:false,
          value:''
        })
      }
    },1000)
  },
  // 清空历史记录
  clearSearch(){
    wx.removeStorageSync('food');
    this.setData({oftenSearch: []});
  },
  // 跳转详情页
  gotoDetail(e){
    const itemId = e.currentTarget.dataset.itemId;

    if(this.data.fromId == 1){
      // console.log(123);
      wx.navigateTo({
        url: `../../pages/foodDetail/foodDetail?foodId=${itemId}&recordTime=${this.data.time}&recordDate=${this.data.recordDate}`,
      })
    }else{
      this.setData({show: true})
      const selected = this.data.searchData.find(item=> item.id === itemId);
      this.setData({
        selectedSport: selected,
        unitHeat: selected.heat
      })
    }
  },
  gotoSearch(e){
    const item = e.currentTarget.dataset.item;
    fetch(`/food/search?value=${item}`).then(res=>{
      this.setData({
        // foodData: res.data,
        searchData: res.data,
        isShow: true,
      })
    })
  },
  onClose(e){
    const recordSport = e.detail.recordSport;
    this.setData({
      show: false,
      recordSport
    })
    this.addRecord();
  },
  addRecord(){
    fetch('/sportsrecord/add',{
      sportsRecord: this.data.recordSport
    },'post').then(res=>{
      if(res.code === 200){
        wx.showToast({
          title: '打卡成功',
          icon: 'success'
        })
        wx.navigateTo({
          url: `../foodRecord/foodRecord?recordTime=${this.data.time}&recordDate=${this.data.recordDate}`,
        })
      }
    }).catch(err=>{
      this.addRecord();
    })
  },
  closePopup(){
    this.setData({
      show: false
    });
  },
})